import React from "react";
import { View, Text, ScrollView, TouchableOpacity } from "react-native";
import Echarts from "native-echarts";
import { DateUtils } from "../../utils/Utils";
import Config from "../../config";
import SizeUtils from "../../common/SizeUtils";
import BasePage from "../common/BasePage";
import BaseItem from "../common/BaseItem";
import TImage from "../../components/TImage";
import SportReadLocalDataAction from "../../actions/sport/SportReadLocalDataAction";
import SportRequestSelfListDataAction from "../../actions/sport/SportRequestSelfListDataAction";
const DAY_NUM = 7;
var STEP_DAYS = [];
const Tabs = ["步数分析", "消耗大卡"];
const WEEK = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
export default class SportDataPage extends BasePage {
  constructor(props) {
    super(props);

    this._scrollView = null;
    this._pageWidth = SizeUtils.getWindowSize().width;
    this._pageHeight =
      SizeUtils.getWindowSize().height -
      SizeUtils.translateDesignHeightToCode(80);
    // this._clickTopBtnTimer = null;

    this.state.currentIndex = this.props.pageData.routeData.currentIndex;
    this.state.allSteps = 0;
    this.state.allDistance = 0;
    this.state.healthyData = { step: 0, distance: 0 };
    this.state.updateMark = 0;
    this.state._healthyDataNew = [];

    this._imageWidth = SizeUtils.translateDesignWidthToCode(588);
    this._imageHeight = SizeUtils.translateDesignWidthToCode(470);
    this._healthyDatas = {};
    STEP_DAYS = [];
    this._healthyDataNew = [];
    for (var i = 0; i < DAY_NUM; i++) {
      STEP_DAYS.push(-i);
      this._healthyDatas[-i] = { step: 0, distance: 0 };
      this._healthyDataNew.push({ step: 0, distance: 0, day: -i });
    }
    this._requestData();
  }

  componentDidMount() {
    this._onPressBtn(this.props.pageData.routeData.currentIndex);
  }

  componentWillUpdate(nextProps, nextState) {
    super.componentWillUpdate(nextProps, nextState);
    if (nextState.isUpdate) {
      nextState.isUpdate = false;
      let steps = 0;
      var  arr  =nextState._healthyDataNew.reverse();
      for (var i = 0; i < this._healthyDataNew.length; i++) {
        for (var j = arr.length - 1; j >= 0; j--) {
          var  week  = parseInt(arr[j].week);
            var  tsps  = parseInt(arr[j].steps);
            this._healthyDataNew[week].step = tsps;
            steps += tsps;
        }
      }
      nextState.allSteps = steps;
    }
  }

  _dealEnterPage() {
    this.setState({
      updateMark: this.state.updateMark + 1
    });
  }

  _requestData() {
    new SportRequestSelfListDataAction().call(this);
  }

  //{this._renderBottomBg()}
  // {this._renderStepList()}
  // {this._renderAllSteps()}
  render() {
    return (
      <View
        style={{
          width: SizeUtils.getWindowSize().width,
          height: SizeUtils.getWindowSize().height,
          backgroundColor: "#ffffff",
          paddingTop: Config.paddingTop
        }}
      >
        {this._renderScrollView()}
        {this._renderNavigationBar()}
      </View>
    );
  }

  _renderScrollView() {
    return (
      <ScrollView
        style={{
          width: this._pageWidth,
          height: this._pageHeight
        }}
        ref={ref => (this._scrollView = ref)}
        horizontal={true} // 水平方向
        showsHorizontalScrollIndicator={false} // 水平指示器
        showsVerticalScrollIndicator={false} // 垂直指示器
        pagingEnabled={true} // 开启分页功能
        alwaysBounceHorizontal={false} //弹性拉动一截
        onScroll={this._onScroll.bind(this)}
        scrollEnabled={this.state.scrollEnabled}
      >
        {this._renderBuShuCharts()}
        {this._renderXiaoHaoCharts()}
      </ScrollView>
    );
  }

  getStepData = () => {
    const healthyDataNew = this.state._healthyDataNew;
    if (healthyDataNew.length === 0) {
      return [0, 0, 0, 0, 0, 0, 0];
    }
    return healthyDataNew.map(d => d.steps);
  };

  getWeeksData = () => {
    const healthyDataNew = this.state._healthyDataNew;
    if (healthyDataNew.length === 0) {
      return WEEK;
    }
    return healthyDataNew.map(d => WEEK[Number.parseInt(d.week)]);
  };

  getColData = () => {
    const healthyDataNew = this.state._healthyDataNew;
    if (healthyDataNew.length === 0) {
      return [0, 0, 0, 0, 0, 0, 0];
    }
    return healthyDataNew.map(d => ((d.steps/20).toFixed(1)/1000).toFixed(3));
  };

  // 步数分析
  _renderBuShuCharts() {
    const steps = this.getStepData();
    const allSteps = steps.reduce((a, b) => a + b, 0);
    const option = {
      title: {
        text: ""
      },
      tooltip: {},
      legend: {
        data: []
      },
      xAxis: {
        data: this.getWeeksData(),
        axisLine: {
          lineStyle: {
            color: ["e1e1e1"]
          }
        }
      },
      yAxis: {
        position: "right",
        axisLine: {
          lineStyle: {
            color: ["e1e1e1"]
          }
        }
      },
      series: [
        {
          type: "bar",
          name: "步数",
          data: steps,
          itemStyle: {
            barBorderRadius: SizeUtils.translateDesignWidthToCode(4)
          },
          label: {
            show: true,
            position: "top",
            distance: 5,
            formatter: "{c}",
            color: "#ffffff"
          },
          barWidth: SizeUtils.translateDesignWidthToCode(60)
        }
      ],
      textStyle: {
        color: "#bebebe",
        fontSize: SizeUtils.translateFontSizeToCode(22)
      },
      color: ["#FF4931"]
    };
    return (
      <View
        style={{
          width: SizeUtils.getWindowSize().width,
          height: SizeUtils.getWindowSize().height
        }}
      >
        {this._renderCharts(option)}
        {this._renderBottomContent("步数", parseInt(allSteps / 7), allSteps)}
      </View>
    );
  }
  // 消耗大卡
  _renderXiaoHaoCharts() {
    const col = this.getColData();
    const allCol = col.reduce((a, b) => parseFloat(a)+parseFloat(b), 0).toFixed(3);
    const option = {
      title: {
        text: ""
      },
      tooltip: {},
      legend: {
        data: []
      },
      xAxis: {
        data: this.getWeeksData(),
        axisLine: {
          lineStyle: {
            color: ["e1e1e1"]
          }
        }
      },
      yAxis: {
        position: "right",
        axisLine: {
          lineStyle: {
            color: ["e1e1e1"]
          }
        }
      },
      series: [
        {
          type: "bar",
          name: "消耗大卡",
          data: col,
          itemStyle: {
            barBorderRadius: SizeUtils.translateDesignWidthToCode(4)
          },
          label: {
            show: true,
            position: "top",
            distance: 5,
            formatter: "{c}",
            color: "#ffffff"
          },
          barWidth: SizeUtils.translateDesignWidthToCode(60)
        }
      ],
      textStyle: {
        color: "#bebebe",
        fontSize: SizeUtils.translateFontSizeToCode(22)
      },
      color: ["#FF4931"]
    };
    return (
      <View
        style={{
          width: SizeUtils.getWindowSize().width,
          height: SizeUtils.getWindowSize().height
        }}
      >
        {this._renderCharts(option)}
        {this._renderBottomContent("大卡", (allCol / 7).toFixed(3), allCol)}
      </View>
    );
  }

  _renderBottomContent(title, average, total) {
    return (
      <View
        style={{
          marginTop: SizeUtils.translateDesignHeightToCode(72),
          flexDirection: "row"
        }}
      >
        <View
          style={{
            flex: 1,
            alignItems: "center"
          }}
        >
          <Text
            style={{
              color: "#ff4931",
              fontSize: SizeUtils.translateFontSizeToCode(68)
            }}
          >
            {average}
          </Text>
          <Text
            style={{
              color: "#ff4931",
              fontSize: SizeUtils.translateFontSizeToCode(28)
            }}
          >
            {`平均${title}`}
          </Text>
        </View>
        <View
          style={{
            flex: 1,
            alignItems: "center"
          }}
        >
          <Text
            style={{
              color: "#ff4931",
              fontSize: SizeUtils.translateFontSizeToCode(68)
            }}
          >
            {total}
          </Text>
          <Text
            style={{
              color: "#ff4931",
              fontSize: SizeUtils.translateFontSizeToCode(28)
            }}
          >
            {`总${title}`}
          </Text>
        </View>
      </View>
    );
  }

  _renderCharts(option) {
    return (
      <View
        style={{
          width: SizeUtils.getWindowSize().width,
          height: SizeUtils.translateDesignHeightToCode(800)
        }}
      >
        <Echarts
          option={option}
          height={SizeUtils.translateDesignHeightToCode(800)}
        />
      </View>
    );
  }

  _renderNavigationBarTitle() {
    return (
      <View
        style={{
          width: SizeUtils.getWindowSize().width / 2,
          height: SizeUtils.translateDesignHeightToCode(80),
          flexDirection: "row",
          justifyContent: "center",
          alignItems: "center",
          // borderBottomWidth: SizeUtils.translateDesignNumToCode(3),
          // borderColor: "#eeeeee",
          backgroundColor: "#ffffff"
        }}
      >
        {this._getButton(0)}
        {this._getButton(1)}
      </View>
    );
  }

  _onPressBtn(index) {
    // console.log("_onPressBtn", index);
    // if (this._clickTopBtnTimer) {
    //   return;
    // }
    // this._clickTopBtnTimer = setTimeout(() => {
    //   this.setState({
    //     scrollEnabled: Platform.OS === "ios"
    //   });
    //   this._clearClickTopBtnTimer();
    // }, 500);
    this.setState(
      {
        scrollEnabled: true
      },
      () => this._scrollView.scrollTo({ x: index * this._pageWidth })
    );
  }

  _getButton(index) {
    return (
      <TouchableOpacity
        onPress={() => this._onPressBtn(index)}
        style={{
          width: SizeUtils.getWindowSize().width / 2 / Tabs.length,
          height: SizeUtils.translateDesignHeightToCode(80),
          flexDirection: "column",
          justifyContent: "center",
          alignItems: "center"
        }}
      >
        <View
          style={{
            height: SizeUtils.translateDesignHeightToCode(76),
            justifyContent: "center",
            alignItems: "center"
          }}
        >
          <Text
            style={{
              fontSize: SizeUtils.translateFontSizeToCode(28),
              color: index == this.state.currentIndex ? "#db3132" : "#666666"
            }}
          >
            {Tabs[index]}
          </Text>
        </View>
        <View
          style={{
            borderColor: "#db3132",
            borderBottomWidth:
              index == this.state.currentIndex
                ? SizeUtils.translateDesignNumToCode(10)
                : 0,
            width: SizeUtils.translateDesignWidthToCode(100),
            height: SizeUtils.translateDesignHeightToCode(5)
          }}
        />
      </TouchableOpacity>
    );
  }

  // _renderStepList() {
  //   return (
  //     <View
  //       style={{
  //         paddingLeft: SizeUtils.translateDesignWidthToCode(40),
  //         paddingRight: SizeUtils.translateDesignWidthToCode(40),
  //         paddingTop:
  //           SizeUtils.translateDesignHeightToCode(74) + Config.paddingTop,
  //         width:
  //           SizeUtils.getWindowSize().width -
  //           SizeUtils.translateDesignWidthToCode(80),
  //         // height:SizeUtils.getWindowSize().height - Config.paddingTop,
  //         flexDirection: "column",
  //         justifyContent: "center"
  //       }}
  //     >
  //       <ScrollView
  //         style={{
  //           width:
  //             SizeUtils.getWindowSize().width -
  //             SizeUtils.translateDesignWidthToCode(80),
  //           height: this._imageHeight,
  //           flexDirection: "row"
  //         }}
  //         horizontal={true} // 水平方向
  //         showsHorizontalScrollIndicator={false} // 水平指示器
  //         showsVerticalScrollIndicator={false} // 垂直指示器
  //         // pagingEnabled={true}    // 开启分页功能
  //         alwaysBounceHorizontal={false} //弹性拉动一截
  //         onScroll={this._onScroll.bind(this)}
  //         scrollEventThrottle={16}
  //       >
  //         {this._healthyDataNew.map((day, index) => {
  //           return this._renderStepItem(day, index);
  //         })}
  //       </ScrollView>
  //       {this._renderProgressView()}
  //     </View>
  //   );
  // }

  _renderBottomBg() {
    return (
      <View style={{ position: "absolute", bottom: 0, left: 0 }}>
        <TImage
          source={require("../../../resource/images/sport/sportData_bom_bg.png")}
          style={{ width: 750, height: 148 }}
        />
      </View>
    );
  }

  _renderAllSteps() {
    return (
      <View
        style={{
          paddingTop: SizeUtils.translateDesignHeightToCode(148),
          flexDirection: "column",
          justifyContent: "center"
        }}
      >
        <Text
          style={{
            fontSize: SizeUtils.translateFontSizeToCode(40),
            color: "#666666",
            width: SizeUtils.getWindowSize().width,
            textAlign: "center"
          }}
        >
          {DAY_NUM + "日总步数: "}
          <Text
            style={{
              fontSize: SizeUtils.translateFontSizeToCode(68),
              color: "#00baff"
            }}
          >
            {"  " + this.state.allSteps}
          </Text>
        </Text>
        {/* <Text style={{fontSize:SizeUtils.translateFontSizeToCode(30), color:"#999999",
          textAlign:"center", paddingTop:SizeUtils.translateDesignHeightToCode(20)}}>
            「总距离: {this.state.allDistance} 米」
        </Text> */}
      </View>
    );
  }

  _renderProgressView() {
    return (
      <View
        style={{
          width:
            SizeUtils.getWindowSize().width -
            SizeUtils.translateDesignWidthToCode(80),
          height: SizeUtils.translateDesignHeightToCode(10),
          justifyContent: "center",
          alignItems: "center",
          paddingTop: SizeUtils.translateDesignHeightToCode(50)
        }}
      >
        <View
          style={{
            width: SizeUtils.translateDesignWidthToCode(
              50 * STEP_DAYS.length + 20 * (STEP_DAYS.length - 1)
            ),
            flexDirection: "row",
            justifyContent: "space-around",
            alignItems: "center"
          }}
        >
          {STEP_DAYS.map((day, index) => {
            return this._renderProgress(day, index);
          })}
        </View>
      </View>
    );
  }

  _onScroll(event) {
    let x = event.nativeEvent.contentOffset.x;
    let index = Math.round(x / this._pageWidth);
    if (this.state.currentIndex != index) {
      this.setState({
        currentIndex: index
      });
    }
  }

  // _renderStepItem(data, index) {
  //   return (
  //     <Item
  //       data={data}
  //       key={index}
  //       index={index}
  //       updateCallback={healthyData =>
  //         this._itemUpdateCallback(-data.day, healthyData)}
  //       updateMark={this.state.updateMark}
  //     />
  //   );
  // }

  _itemUpdateCallback(day, healthyData) {
    console.log("_itemUpdateCallback", day, healthyData);
    if (this._healthyDataNew[day] != undefined) {
      this._healthyDataNew[day].step = healthyData.step;
      let allSteps = 0;
      let allDistance = 0;
      for (var i = 0; i < this._healthyDataNew.length; i++) {
        allSteps += this._healthyDataNew[i].step;
        allDistance += this._healthyDataNew[i].distance;
      }

      this.setState({
        allSteps: allSteps,
        allDistance: allDistance
      });
    } else {
      console.warn("数据错误", day);
    }
  }

  _renderProgress(data, index) {
    return (
      <View
        key={index}
        style={{
          width: SizeUtils.translateDesignWidthToCode(30),
          height: SizeUtils.translateDesignHeightToCode(6),
          backgroundColor:
            this.state.currentIndex == index ? "#6ce3ff" : "#daebfe"
        }}
      />
    );
  }
}

// class Item extends BaseItem {
//   constructor(props) {
//     super(props);
//     this.getStepTimer = null;
//     this.state.healthyData = this.props.data;
//     var value = -this.props.data.day;
//     if (value == 0) {
//       this.getStepTimer = setInterval(() => {
//         new SportReadLocalDataAction().call(this, {
//           type: ["step", "distance"],
//           day: 0
//         });
//       }, 10000);
//     }
//   }

//   componentDidMount() {
//     this._requestData();
//   }

//   componentWillUpdate(nextProps, nextState) {
//     if (nextProps.updateMark != this.props.updateMark) {
//       this._requestData();
//     }
//     if (nextState.updateDataMark == true) {
//       nextState.updateDataMark = false;
//       this.props.updateCallback(nextState.healthyData);
//     }
//   }
//   componentWillUnmount() {
//     this._clearInterval();
//   }
//   _clearInterval() {
//     if (this.getStepTimer != null) {
//       clearInterval(this.getStepTimer);
//       this.getStepTimer = null;
//     }
//   }

//   render() {
//     return (
//       <View
//         style={{
//           marginRight: SizeUtils.translateDesignWidthToCode(44),
//           marginLeft:
//             this.props.index == 0
//               ? SizeUtils.translateDesignWidthToCode(40)
//               : 0,
//           width: SizeUtils.translateDesignWidthToCode(588),
//           height: SizeUtils.translateDesignWidthToCode(470)
//         }}
//       >
//         <View style={{ position: "absolute", top: 0 }}>
//           <TImage
//             source={require("../../../resource/images/sport/sportDate_bg.png")}
//             style={{ width: 588, height: 467 }}
//           />
//         </View>
//         <View
//           style={{
//             paddingTop: SizeUtils.translateDesignHeightToCode(134),
//             flexDirection: "column",
//             backgroundColor: "#00000000"
//           }}
//         >
//           <Text
//             style={{
//               fontSize: SizeUtils.translateFontSizeToCode(30),
//               color: "#ffffff",
//               textAlign: "center",
//               fontWeight: "bold",
//               backgroundColor: "#00000000"
//             }}
//           >
//             {this._getStepText(this.props.data.day)}
//           </Text>
//           {/* <Text style={{fontSize:SizeUtils.translateFontSizeToCode(30),
//               color:"#ffffff", textAlign:"center", fontWeight:"bold",
//               paddingTop:SizeUtils.translateDesignHeightToCode(20)}}>
//             {this._getDistanceText(this.props.data)}
//           </Text> */}
//         </View>
//       </View>
//     );
//   }

//   _getStepText(day) {
//     let text = day + "日";
//     if (day === 0) {
//       text = "今日";
//     } else {
//       let date = new Date();
//       let time = new Date().setHours(0, 0, 0, 0);
//       time += day * 24 * 60 * 60 * 1000;
//       date.setTime(time);
//       text = date.getMonth() + 1 + "月" + date.getDate() + "日";
//     }
//     return text + "步数: " + this.state.healthyData.step;
//   }

//   _getDistanceText() {
//     return "距离 : " + this.state.healthyData.distance + " 米";
//   }

//   _requestData() {
//     var value = -this.props.data.day;
//     if (value == 0) {
//       new SportReadLocalDataAction().call(this, {
//         type: ["step", "distance"],
//         day: -this.props.data.day
//       });
//     }
//   }
// }
